package com.wutianyi.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.wutianyi.session.DBSessionFactory;
import com.wutianyi.session.SessionFactory;
import com.wutianyi.web.wrapper.SessionHttpServletRequest;

/**
 * @author hanjiewu
 * 
 */
public class SessionFilter implements Filter {

	private SessionFactory sessionFactory;
	private final String SESSION_ID_COOKIE_NAME = SessionHttpServletRequest.class
			.getName() + "_JSESSIONID";
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		sessionFactory = new DBSessionFactory();

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			String sessionId = getSessionId((HttpServletRequest) request);
			chain.doFilter(new SessionHttpServletRequest(
					(HttpServletRequest) request, sessionFactory, sessionId),
					response);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			HttpSession httpSession = sessionFactory
					.getHttpSession(null, false);
			if (null != httpSession) {
				System.out.println("saving httpsession ... ..." + httpSession.getId());
				sessionFactory.saveSession(httpSession);
				if (httpSession.isNew()) {
					Cookie cookie = new Cookie(SESSION_ID_COOKIE_NAME,
							httpSession.getId());
					cookie.setMaxAge(httpSession.getMaxInactiveInterval());
					((HttpServletResponse) response).addCookie(cookie);
				}
				sessionFactory.remove();
			}

		}

	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
	private String getSessionId(HttpServletRequest request) {
		String sessionId = request.getParameter(SESSION_ID_COOKIE_NAME);
		if (StringUtils.isBlank(sessionId)) {
			Cookie[] cookies = request.getCookies();
			if (null != cookies) {
				for (Cookie cookie : cookies) {
					if (SESSION_ID_COOKIE_NAME.equals(cookie.getName())) {
						sessionId = cookie.getValue();
					}
				}
			}
		}
		return sessionId;
	}

}
